/*
 * @(#) BaseAction.java 2010-9-2
 *
 * Copyright (c) 2010, Strong Technology Inc. All Rights Reserved.
 * Strong System Inc. CONFIDENTIAL
 */
package cn.strong.gweva.common.presentation.action;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.exception.ParsePropertyException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import cn.strong.gweva.common.business.entity.BaseExcelExportEntity;
import cn.strong.gweva.common.business.entity.LoginEntity;
import cn.strong.gweva.common.execption.ServiceException;
import cn.strong.gweva.common.util.Constants;
import cn.strong.gweva.common.util.DateUtil;
import cn.strong.gweva.common.util.MessageCode;
import cn.strong.gweva.common.util.MessageUtil;
import cn.strong.gweva.common.util.SessionUtil;
import cn.strong.gweva.common.util.StringUtil;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Action基类
 * 
 * @author lilanfei
 * @version 1.0
 * @since 2010-9-2
 */
public class BaseAction extends ActionSupport
{
	/**
	 * <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = -8446356653003693458L;

	/** 写日志 */
	protected Log log = LogFactory.getLog(this.getClass());
	
	/** 内网系统错误 */
	public static final String SYS_ERROR = "sysError";
	/** 未登录*/
	public static final String NO_LOGIN = "noLogin";
	/** 没权限*/
	public static final String NO_PERMS = "noPerms";
	/** 列表*/
	public static final String LIST = "list";
	/** 详细*/
	public static final String DETAIL = "detail";
	/** 新增*/
	public static final String ADD = "add";
	/** 修改*/
	public static final String MODIFY = "modify";
	
	/** 新增,修改是否成功标识 */
	private String isSuccess;
	
	/** 操作类型 */
	private String operateType = "";

	/** 显示在错误页面的消息 */
	private String errorPageMsg = "";
	
	protected HttpServletResponse response;
	
	/**
	 * @return isSuccess
	 */
	public String getIsSuccess()
	{
		return isSuccess;
	}

	/**
	 * @param isSuccess isSuccess
	 */
	public void setIsSuccess(String isSuccess)
	{
		this.isSuccess = isSuccess;
	}
	
	/**
	 * 共通异常处理
	 * 
	 * @param ex
	 */
	public String processException(Exception ex)
	{
		// 消息Code
		String errorCode = ex.getMessage();

		log.debug("setErrorMsg ST");
		log.debug("error getMessage=" + ex.getMessage());
		log.debug("error getClass=" + ex.getClass());
		log.error("error", ex);

		if (ex instanceof ServiceException)
		{
			ServiceException se = (ServiceException)ex;
			String msg = MessageUtil.getMsg(se.getKey(), se.getReplacements());
			if(StringUtil.isEmpty(msg))
			{
				msg = se.getKey();
			}
			if (this.getLoginUser() != null)
			{
				log.error(this.getLoginUser().getUserName() + " " + ex.getClass() + " "
						+ errorCode);
			}

			if (MessageCode.SYSTEM_ERROR_MSG.equals(errorCode))
			{
				this.writeErrorPageMsg("错误", msg);
				return SYS_ERROR;
			}
			else
			{
				this.isSuccess = msg;
				return ERROR;
			}
		}
		else
		{
			if (this.getLoginUser() != null)
			{
				log.error(this.getLoginUser().getUserName() + " " + ex.getClass(), ex);
			}
			this.writeErrorPageMsg("错误", MessageUtil
					.getMsg(MessageCode.SYSTEM_ERROR_MSG));

			return SYS_ERROR;
		}
	}

	/**
	 * 往错误页面消息
	 * 
	 * @param operateType 操作类型名称
	 * @param errorPageMsg 消息
	 */
	public void writeErrorPageMsg(String operateType, String errorPageMsg)
	{
		this.operateType = operateType;
		this.errorPageMsg = errorPageMsg;
	}
	
	/**
	 * 获取用户登录信息
	 * @return
	 */
	protected LoginEntity getLoginUser()
	{
		return SessionUtil.getLoginEntity();
	}

	/**
	 * 判断当前用户是否超时
	 * 
	 * @return 超时标志
	 */
	protected boolean isTimeout()
	{
		if (ActionContext.getContext().getSession().get(Constants.SESSION_LOGIN_USER_INF) == null)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	/**
	 * 取得请求的URL
	 * 
	 * @return 请求的URL
	 */
	protected String getRequestPath()
	{
		return (String)ServletActionContext.getRequest().getServletPath();
	}

	/**
	 * 获取IP地址
	 * 
	 * @return IP地址
	 */
	protected String getIpaddress()
	{
		return ServletActionContext.getRequest().getRemoteAddr();
	}
	
	public void process(BaseExcelExportEntity entity, HSSFWorkbook book)
	{
		response = ServletActionContext.getResponse();
		response.setContentType("application/octet-stream");
		// 取得excel下载文件名
		String strFileName = (entity != null) ? entity.getDownloadFileName() : "epps";
		// 设置excel响应的header
		response.setHeader("Content-Disposition", "attachment; filename="
				+ formatFileName(strFileName));
		try
		{
			// 取得响应的输出流
			OutputStream out = response.getOutputStream();
			// 将excel的workbook信息写到输出流中
			book.write(out);
			// 清楚缓存区域、输出响应
			out.flush();
		}
		catch (ParsePropertyException e)
		{
		}
		catch (FileNotFoundException e)
		{
		}
		catch (IOException e)
		{
		}
	}
	
	/**
	 * 格式化文件名
	 * 
	 * @param string
	 *            fileName
	 * @return String 格式化的文件名
	 * */
	private String formatFileName(String fileName) {
		if (fileName == null) {
			fileName = "evims";
		} else if (fileName.length() > 12) {
			fileName = fileName.substring(0, 8) + "...";
		}
		String strFileName = fileName + "_"
				+ DateUtil.formatDate(new Date(), DateUtil.DATE_PATTERN_03)
				+ ".xls";
		try {
			strFileName = new String(strFileName.getBytes("GB2312"),
					"ISO8859_1");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
		return strFileName;
	}
	
	/**
	 * @return operateType
	 */
	public String getOperateType()
	{
		return operateType;
	}

	/**
	 * @param operateType operateType
	 */
	public void setOperateType(String operateType)
	{
		this.operateType = operateType;
	}

	/**
	 * @return errorPageMsg
	 */
	public String getErrorPageMsg()
	{
		return errorPageMsg;
	}

	/**
	 * @param errorPageMsg errorPageMsg
	 */
	public void setErrorPageMsg(String errorPageMsg)
	{
		this.errorPageMsg = errorPageMsg;
	}

	/**
	 * @return response
	 */
	public HttpServletResponse getResponse()
	{
		return response;
	}

	/**
	 * @param response response
	 */
	public void setResponse(HttpServletResponse response)
	{
		this.response = ServletActionContext.getResponse();
	}
}